package com.zxj.geekstudy.other.proxy.cglib;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 验证cglib可直接代理接口，不需要有实现类
 */
public class SampleClass2 {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(SampleInterface.class);
        MethodInterceptor interceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                System.out.println("before method run...");
                System.out.println("after method run...");
                return "00";
            }
        };
        MethodInterceptor interceptor1 = new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                System.out.println("before method run1...");
                System.out.println("after method run1...");
                return "11";
            }
        };
        enhancer.setCallbackFilter((method) ->{
            String methodName = method.getName();
            if ("test".equals(methodName)) {
                return 0; // eat()方法使用callbacks[1]对象拦截。
            }
            return 1;   //其他方法使用callbacks[0]对象拦截。
        });
        enhancer.setCallbacks(new Callback[]{interceptor, interceptor1});
        SampleInterface sample = (SampleInterface) enhancer.create();
        System.out.println(sample.test());
        System.out.println(sample.test1());
    }
}
